//the text to link code (uriaggressive) is from Kim A. Brandt. See http://userscripts.org/scripts/show/7122
 const SS_uriaggressive = /[a-z][a-z0-9+-.]*:((\/\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:]|%[a-f0-9]{2})*@)?((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])|([a-z0-9-\._~!$&'\(\)\/\*\+,;=]|%[a-f0-9]{2})+(:[0-9]+)?(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)|(\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)?)|(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*))+(\?([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?(#([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?/i;
 const SS_uri = /((http)s?|(ftp)|(mailto)):((\/\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:]|%[a-f0-9]{2})*@)?((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])|([a-z0-9-\._~!$&'\(\)\/\*\+,;=]|%[a-f0-9]{2})+(:[0-9]+)?(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)|(\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)?)|(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*))+(\?([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?(#([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?/i;
 
 const SS_uri2_57 = /[a-z0-9+-.(@)?]*\b\.((name)|([A-za-z]){2,3})\b([A-Za-z0-9$_+-=!*();&%/?:~.]*)?/i;
 const SS_uri2_56 = /[a-z0-9+-.(@)?]*\b\.(com|net|org|edu|uk|au)\b([A-Za-z0-9$_+-=!*();&%/?:~.]*)?/i;
 
 const SS_uri2 = /[a-z0-9+-.(@)?]*\b\.(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=()&%/?:~])*([\.,*;!](?=[-A-Za-z0-9$_+=*();&%/?:~]))*)*/i;
 const SS_uri2_63_1 = /(([-A-Za-z0-9$_+=()&%/?:~])*([\.,*;!@](?=[-A-Za-z0-9$_+=*();&%/?:~]))*)*\b\.(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=()&%/?:~])*([\.,*;!](?=[-A-Za-z0-9$_+=*();&%/?:~]))*)*/i;
 const SS_uri2RnD = /(([-A-Za-z0-9$_+=&%~])*([\.@](?=[A-Za-z0-9]))?)*\.(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=()&%/?:~])*([\.,*;!](?=[-A-Za-z0-9$_+=*();&%/?:~]))*)*/i;

 const SS_illegal = /^(a|button|label|legend|option|script|select|style|textarea|title)$/i;
 
 var SS_prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
 var SS_alertTimeOut = 1500;
 
 const SS_ulreplacement = "<u>$1</u>";
		  
//pref consts		
const SMACK_AUTOURL   = "extensions.swaksmack.autourl_boolpref1";  
const SMACK_EASYURL   = "extensions.swaksmack.easyurl_boolpref1";
const SMACK_MAXURL = "extensions.swaksmack.maxurl_boolpref1";
const SMACK_MAXLENGTH = "extensions.swaksmack.maxurllength_intpref";
const SMACK_TRUNCURL = "extensions.swaksmack.truncurl_stringpref";
const SMACK_OUTWITALERT = "extensions.swaksmack.outwitwarn_pref1";
const SMACK_OUTWITVOTEALERT = "extensions.swaksmack.outwitvotewarn_pref1";
const SMACK_OUTWITRANDOM = "extensions.swaksmack.outwitrandom_pref1";
const SMACK_GURUGUESSALERT = "extensions.swaksmack.guruguesswarn_pref1";
const SMACK_POLLINTERVAL = "extensions.swaksmack.pollinterval_intpref";

const SMACK_ENABLEHL = "extensions.swaksmack.enablehl_boolpref1";
const SMACK_IGNORECASEHL = "extensions.swaksmack.ignorecasehl_boolpref1";
const SMACK_IGNORESPHL = "extensions.swaksmack.ignoreselfposts_boolpref1";
const SMACK_ENABLELRHL = "extensions.swaksmack.enableinlrhl_boolpref1";
const SMACK_KEYWORDHL1 = "extensions.swaksmack.keywordshl1_stringpref";
const SMACK_TCHL1 = "extensions.swaksmack.hltextcolor1_stringpref";
const SMACK_BTCHL1 = "extensions.swaksmack.hlbkcolor1_stringpref";
const SMACK_UNDERLINEHL1 = "extensions.swaksmack.hlunderline1_boolpref1";
const SMACK_ITALICHL1 = "extensions.swaksmack.hlitalic1_boolpref1";
const SMACK_BOLDHL1 = "extensions.swaksmack.hlbold1_boolpref1";
const SMACK_WORDONLYHL1 = "extensions.swaksmack.wordonlyhl_boolpref1";
const SMACK_USERNAMEHL1 = "extensions.swaksmack.usernamehl1_stringpref";
const SMACK_IGNORELIST1 = "extensions.swaksmack.ignorelist1_stringpref";

//div ids used to find outwit opt in and answer elements
const SMACK_OUTWITCHATDIV = "chatPost";  // was "chat", commentInfo
const SMACK_COMMENTTEXT = "commentText";
const SMACK_COMMENTNICK = "chatNick";
const SMACK_COMMENTAVATAR = "chatAvatarContainer";
const SMACK_OUTWITCOMMENTDIV = "comment_comment";
const SMACK_PMDIV = "messagesContainer";
const SMACK_OUTWITCAPDIV = "captchaBox";
const SMACK_OUTWITANSWERDIV = "outwitAnswer";
const SMACK_OUTWITGURUGUESSDIV = "guruMakeGuess";
const SMACK_DEALDIV = "deal";
const SMACK_OUTWITCONDIV = "outwitContainer";
const SMACK_GURUCONDIV = "guruContainer";
//needed???
const SMACK_SHOWNAMEVALUE = "showName";
const SMACK_SHOWNAMEDIV = "The Daily Smack with Smack Daddy";

const SMACK_ALERT_OUTWITOPTIN = 1;
const SMACK_ALERT_OUTWITVOTE = 2;
const SMACK_ALERT_GURUGUESS = 10;

var SS_chatcss = "@namespace url(http://www.w3.org/1999/xhtml);  /* Change color of  links */ #chat div.commentText a:visited, #chat div.commentText a:link  { color: #FF7800 !important; } ";


//REMOVWE var outwitAlertPref = true;
var SS_outwitAlertAck = false;
var SS_outwitVoteAck = false;
//REMOVE var outwitVoteAlertPref = true;



var SS_ggListenerAdded = false;
//REMOVE var guruguessAlertPref = true;
var SS_guruguessAlertAck = false;
var SS_keywordDisplayLength = 15;

var SS_window;
var SS_doc;


//array to hold the chat div ids
var SS_chatIdArray = new Array();
//var _tabcontainer = gBrowser.tabContainer;

var SS_dynamicKeywords = new Array();

var SS_colorCommentMatchArray = new Array();

var SS_UID;
var SS_ggcalc;
var SS_GGCalcWindow;
//the alert manager
var SS_AM;
//the statusbar manager
var SS_SBM = null;

 function checkHost(doc) {
 	 	host = doc.location.host;
 	 	//alert(host);
 	 	if (host == 'www.jellyfish.com' || host == 'jellyfish.com' || host==null || host=='')
 	 		return true;
 	 	return false;	
 }
 
 function isPMArea(doc) {

 	if (doc == null) doc=content.document;
 	var hostPath = doc.location.pathname;
 	var matches = hostPath.match("/shoppers/me/messages");
 	if (matches != null) {
 		return true;
	}
	return false;
 }
 
  function isSmackShopArea(doc) {
  	if (doc == null) doc = content.document;
 	var hostPath = doc.location.pathname;
 	var matches = hostPath.match("/smacktv/channel");
 	if (matches != null) {
 		return true;
	}
	return false;
 }
 
  function isLRArea(doc) {
  	if (doc == null) doc = content.document;
  	var lrDiv = doc.getElementById('livingRoomName');
 		if (lrDiv != null) return true;
	return false;
 }

 function chatLinkColor(doc) {
 	if (doc == null) doc = content.document;
 				var heads = doc.getElementsByTagName("head");
			if (heads.length > 0) {
				var node = doc.createElement("style");
				node.innerHTML = SS_chatcss;
				node.type = "text/css";
				heads[0].appendChild(node); 
			}
 }
 //from http://robertnyman.com/js/getElementsByClassName.js
function getElementsByClassName_ORG(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];		
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}	
	}
	return (arrReturnElements)
}

function _getElementsByXPath(expression,parent) {
    var results = [];
    var query = document.evaluate(expression, parent || window.content.document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (var i = 0, length = query.snapshotLength; i < length; i++)
        results.push(query.snapshotItem(i));
    return results;
};
function getElementsByClassName(className,parent) {
    var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
    return _getElementsByXPath(q,parent);
}

function buildClassNameRegex(strClassName) {
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	return oRegExp;
}

function getElementsByClassName_OLD(oElm, strTagName, oRegExp){
	if (oRegExp == null) return;
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	//strClassName = strClassName.replace(/\-/g, "\\-");
	//var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];		
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}	
	}
	return (arrReturnElements)
}

 function buildSearchString(searchArray) {
 	var searchreg = null;
 	if (searchArray == null) return searchreg;
	for (var i=0; i<searchArray.length;i++){
		if (searchArray[i] == null || searchArray[i]== "") continue;
		if (searchreg == null) {
			
			searchreg = SS_escapeRegExLiterals(searchArray[i].trim());
			continue;
		}
		searchreg = searchreg + '|' +  SS_escapeRegExLiterals(searchArray[i].trim()); 
	}
	return searchreg;
 }
 

 function commentColor(element, doc) {
 	///////////////////////
 
  if (isLRArea(doc) == true && SS_getPreference(SMACK_ENABLELRHL) == false) {
 		return;
 	}
 	var keywords = SS_getPreference(SMACK_KEYWORDHL1);
	var usernames =SS_getPreference(SMACK_USERNAMEHL1);
	var ignorelist =SS_getPreference(SMACK_IGNORELIST1);
	
  var commentPosts = getElementsByClassName("chatPost",element);
	var chatPost = commentPosts[0];
  if (chatPost == null) return;
	var commentTexts = getElementsByClassName(SMACK_COMMENTTEXT,chatPost);
	var chatNick = getElementsByClassName(SMACK_COMMENTNICK,chatPost);  //"chatNick" "chatAvatarContainer"
	if (commentTexts == null || chatNick == null) return;
	
	//check post against ignore list
	if (ignorelist != null && ignorelist != "") {
		ignorelist = ignorelist.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(','); // Allow for spaces in usernames
		ignorelist = buildSearchString(ignorelist);
		//ending with a | or , can be bad
		ignorelist = ignorelist.replace(/(\|$)|(,$)/,'');
		//alert(usernames);
		var ignorelistRegExp = new RegExp(ignorelist,"ig");
  	var ignoreListMatch = isUsernameMatch(chatNick[0],ignorelistRegExp);
  	if (ignoreListMatch) {
  		chatPost.style.display='none';
  		return;
  	}
	}
	
 	var chatRegExp = null;
  
 			//TODO --refactor this into something a bit cleaner
 			var searchFound = false;
 			if (keywords != null && keywords.length >0) {
 	 			keywords = keywords.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(','); // Allow for spaces in usernames
 				keywords = buildSearchString(keywords);
 				searchFound = true;
 			}
 	 		if (SS_dynamicKeywords != null && SS_dynamicKeywords.length >0) {
 	 			var dwords = buildSearchString(SS_dynamicKeywords);
 	 	//		alert('dwords pre cat ' + dwords);
 	 			if (keywords != null && keywords.length >0) keywords = keywords + '|' + dwords;
 	 			else keywords = dwords;
 	 			searchFound = true;
 	 		}
 			
 			//only build regex if we have something to build--otherwise things go very bad
			if (searchFound == true) {
				
				keywords = keywords.replace(/(\|$)|(,$)/g,'');

				keywords = '(' + keywords + ')';
				if(SS_getPreference(SMACK_IGNORECASEHL) == true) chatRegExp = new RegExp(keywords,"ig");  //was ig
				else chatRegExp = new RegExp(keywords,"g"); //was "g"
			}

 	
 	
 	///////////////////////
 	

		//
		/*
	//	alert('chatNick[0].textContent ' + chatNick[0].textContent);
		if (chatNick[0].textContent =='01mm6') {
			alert('01mm6 post hid');
			chatPost.style.display='none';
			return;
		}
		
		//
		*/
		var keywordMatch = false;
		var userNameMatch = false;
		var highlightKeywordsOnly = SS_getPreference(SMACK_WORDONLYHL1);
		if (chatRegExp != null) {
			keywordMatch = colorByComment(commentTexts[0],chatRegExp, highlightKeywordsOnly);
		}

	
		if (usernames != null && usernames != "") {
			usernames = usernames.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(','); // Allow for spaces in usernames
 			usernames = buildSearchString(usernames);
 			//ending with a | or , can be bad
 			usernames = usernames.replace(/(\|$)|(,$)/,'');
 			//alert(usernames);
			var usernameRegExp = new RegExp(usernames,"ig");
	  	userNameMatch = colorByUsername(chatNick[0],usernameRegExp);
		}
	

		

		if (keywordMatch == true && highlightKeywordsOnly == false) {
				var bkgrdColor = SS_getPreference(SMACK_BTCHL1);
				//chatPost.style.background='#'+ bkgrdColor;
				chatPost.style.background = bkgrdColor;
				var textColor = SS_getPreference(SMACK_TCHL1);
				//chatPost.style.color='#'+ textColor;
				chatPost.style.color = textColor;
				updateStatusbarKeyword(1);
				return;
		}
		
		//if matched on username, highlight entire post
		if (userNameMatch) {
			var bkgrdColor = SS_getPreference(SMACK_BTCHL1);
			//chatPost.style.background='#'+ bkgrdColor;
			chatPost.style.background = bkgrdColor;
			var textColor = SS_getPreference(SMACK_TCHL1);
			//chatPost.style.color='#'+ textColor;
			chatPost.style.color = textColor;
			//updateStatusbarKeyword(2);
		}
		
		if (userNameMatch || keywordMatch) {
			updateStatusbarKeyword(2);
		}
		
		
}

function updateStatusbarKeyword(c) {
	if (SS_SBM == null) {
		SS_SBM = new StatusBarManager();
		var sb1 = document.getElementById('swak-sb-kw-status');
		SS_SBM.setKWStatusBarPanel(sb1);
	}
	SS_SBM.flashKeywordButton(5);
}
 
    function colorByComment(element, oRegExp, highlightKeywords) {
 	if (element == null || oRegExp == null) return false;
 	if (highlightKeywords == null) highlightKeywords = false;
 	var underlineMatch = SS_getPreference(SMACK_UNDERLINEHL1);
	var matches;
	var inputText = element.textContent;

	var matchFound = false;
 	
 		//fix href links and so that we don't try to color/underline--will break link			
 	var badToColor = element.getElementsByTagName("a");	

 		//		alert('regex ' + oRegExp);	
	while ((matches = oRegExp.exec(inputText)) != null) {
		
		matchFound = true;
		if (underlineMatch == false && highlightKeywords == false) break;
		//for now don't attempt to color/underline as the innerhtml replace will destroy the hrefs
		if (badToColor != null && badToColor[0] !=null) break;
		
					
		var text = matches[0];
		
		var lastKWMatchIndex = SS_colorCommentMatchArray.indexOf(text);
		if (lastKWMatchIndex != -1) {
			continue;

		}
	//	alert('matches: ' + matches);

		 SS_colorCommentMatchArray.push(text);
		 var regextext = SS_escapeRegExLiterals(text);


	//create a group that will define $1 in the regex
		regextext = '(' +regextext + ')';

		var mRegExp = new RegExp(regextext,"g");
		/*
		var newtext = text;
		if (underlineMatch == true) {
			newtext = '<u>'+text+'</u>';
			//newtext = '&lt;u&gt;'+text+'&lt;/u&gt;';
		}
		if (highlightKeywords == true) {
			newtext = '<span style=\"color:' + SS_getPreference(SMACK_TCHL1) +';background:' + SS_getPreference(SMACK_BTCHL1) + '\">' + newtext + '</span>';	
		}
		*/

	//	element.innerHTML = element.innerHTML.replace(mRegExp, newtext);

		//tag the found keyword(s) by warpping them in the UID
	  var taggedMatches = "\u0009$1\u0009";
		element.textContent = element.textContent.replace(mRegExp, taggedMatches);
					
	}
	
	//now replace the tagged matched words for underlined/highlighted words
	if (matchFound && (underlineMatch || highlightKeywords)) {
		// <([^>]*)>
		
		//replace tagged words wrapped in the UID
		//opps--uid of numbers messes up numbers in posts
		//var replacement = "#" + SS_UID + "#\(\[^#" + SS_CUID + "#\]*\)#" + SS_CUID + "#";	
		//var replacement = "<\(\[^>\]*\)>";	
		var replacement = "\u0009\(\[^\u0009\]*\)\u0009";
		var repRegEx = new RegExp(replacement,"g");
		
		var pass2replace = "$1";
		if (underlineMatch == true) {
			pass2replace = SS_ulreplacement;
		}
	
		if (highlightKeywords == true) {
			pass2replace = '<span style=\"color:' + SS_getPreference(SMACK_TCHL1) +';background:' + SS_getPreference(SMACK_BTCHL1) + '\">' + pass2replace + '</span>';
		}
	
		//replace all the tagged words in one replace of the innerhtml
		element.innerHTML = element.innerHTML.replace(repRegEx, pass2replace);

	}
	
	SS_colorCommentMatchArray = [];
	return matchFound;

 }
 
 function isUsernameMatch(element, oRegExp) {
 	if (element == null || oRegExp == null) return false;
 	var matchFound = false;
 	var matches = oRegExp.exec(element.textContent);
		if (matches != null) {
			matchFound = true;
			// draws box around username element.style.border='2px solid #ccc';
		}
		return matchFound;
 }
 
 function colorByUsername(element, oRegExp) {
 	if (element == null || oRegExp == null) return false;
 	var matchFound = false;
 	var matches = oRegExp.exec(element.textContent);
		if (matches != null) {
			matchFound = true;
			// draws box around username element.style.border='2px solid #ccc';
		}
		return matchFound;
 }
 
 function executePMLink(commentDiv, doc) {
 	if (doc == null) doc = content.document;
 	var chatDiv = doc.getElementById(commentDiv);
  var elements = doc.evaluate(".//text()", chatDiv, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
  if (elements == null) return;
  for (var i = 0; i < elements.snapshotLength; i++) textToLink(elements.snapshotItem(i), doc);
 }
 
 function execute(commentDiv, bool_highlight, doc)
 {
  if (doc == null) return;
 	if (bool_highlight == null) bool_highlight = true;
 
 	var elements = doc.evaluate(".//text()", commentDiv, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
 	for (var ii = 0; ii < elements.snapshotLength; ii++) textToLink(elements.snapshotItem(ii), doc);

	if (SS_getPreference(bool_highlight == true && SMACK_ENABLEHL) == true) {
			commentColor(commentDiv,doc);
	}
		

 }

 function textToLink(element, doc)
 {
     if (element.parentNode.tagName.match(SS_illegal)) return;
     var generousMatch = SS_getPreference(SMACK_EASYURL);
     var matches = element.nodeValue.match(SS_uri);
     if (matches != null) {
	     var text = matches[0];
	     var index = element.nodeValue.indexOf(text);
	     if (index == 0)
	     {
	         if (element.nodeValue.length > text.length) textToLink(element.splitText(text.length), doc);
	         var link = doc.createElement("a");
	         //TEST for fixing link ref that have puncuation on the end
	         var newurl = element.nodeValue.replace(/([\.!,;:\*]*)$/i,'');
	         link.href = newurl;
	         //_TEST
	         ///073107 link.href = element.nodeValue;
	         link.rel="external";
	         element.parentNode.insertBefore(link, element);
	         link.appendChild(element); // TEXT TO LINK
	         slimFastUrl(element); 
		     }
		     else textToLink(element.splitText(index), doc);
  	 }
  	 else if (generousMatch == true){
  	 	matches = element.nodeValue.match(SS_uri2);
  	 	if (matches != null) {
	     var text = matches[0];
	     var emailFound = false;
	     if (text.indexOf("@") != -1) emailFound = true;
	     var index = element.nodeValue.indexOf(text);
	     if (index == 0)
	     {
	         if (element.nodeValue.length > text.length) textToLink(element.splitText(text.length), doc);
	         var link = doc.createElement("a");
	         var newurl = element.nodeValue.replace(/^([\.!,;:\*]*)/i,'');
	         //link.href = 'http://'+element.nodeValue;
	         link.href = 'http://'+ newurl;
	         if (emailFound == true) {
	         	link.href = 'mailto:'+newurl;
	         }
	         link.rel="external";
	         element.parentNode.insertBefore(link, element);
	         link.appendChild(element); // TEXT TO LINK    
	         slimFastUrl(element);       	
		     }
		     else textToLink(element.splitText(index), doc);
  	 }
  	 }

 }
 
 function slimFastUrl(element){
 	  if(element == null) return;
 	  var trimUrlLength = SS_getPreference(SMACK_MAXURL);
 	  if (trimUrlLength == false) return;
 	  var maxUrlLength = SS_getPreference(SMACK_MAXLENGTH);
 	  if (maxUrlLength <=0) {
 	  	var jellyfishstrings = document.getElementById("swaksmack-strings");
 	  	var error = jellyfishstrings.getString("maxUrlLengthError1");	
 	  	alert(error);
 	  	//var defPrefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService.getDefaultBranch());
 	  	var defPrefs = SS_prefs.getDefaultBranch('extensions.swaksmack.');
			maxUrlLength = defPrefs.getIntPref('maxurllength_intpref');
			SS_prefs.setIntPref(SMACK_MAXLENGTH, maxUrlLength);
 	  }
 	  var clippedUrlEnd=SS_getPreference(SMACK_TRUNCURL);
 	  if (maxUrlLength > 0 && element.nodeValue.length > maxUrlLength){
	 		var replacelength = element.nodeValue.length;
	 		var l1 = clippedUrlEnd.length;
	 		if (l1 == maxUrlLength) l1=0;
			var front = element.substringData(0, maxUrlLength-l1);
			front = front+clippedUrlEnd;
			var tn = document.createTextNode(front);				 
			element.parentNode.replaceChild(tn,element.parentNode.firstChild);
	}
 }
 
 function externalLinks(doc) {
 	if (doc == null) doc = content.document;
 if (!doc.getElementsByTagName) return;
 var anchors = doc.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}

function commentSpellCheck(doc) {
	if (doc == null) doc = content.document;
	var commentdiv = doc.getElementById(SMACK_OUTWITCOMMENTDIV);
	if (commentdiv != null) {
		commentdiv.spellcheck = true;
	}
}


var _checkGuruGuess = false;

function registerChatListeners(doc) {
		var chatDiv = doc.getElementById('chat');

		if (chatDiv != null){
			chatDiv.addEventListener('DOMAttrModified', function(event) {
				//need to to proces the last added chat comment
				while (SS_chatIdArray.length >0) {
					execute(SS_chatIdArray.pop(), true, doc);
					externalLinks(doc);
					}
			}, true);
			
			chatDiv.addEventListener('DOMNodeInserted', function(event) {
						
				while (SS_chatIdArray.length >0) {execute(SS_chatIdArray.pop(), true, doc);}
				
//				var commentPosts = getElementsByClassName("chatPost",event.target);
				//alert('event.target.innerHTML ' + event.target.event.target);
				/*
				if(event.target.innerHTML.indexOf('01mm6') >0)
					alert('01mm6 found');
				}
				*/
				SS_chatIdArray.push(event.target);
				SS_oldState = SS_AM.state;
				SS_AM.updateAlertState(doc);
				
				setTimeout("smackPoll()",SS_alertTimeOut);
				/*
				if (SS_outwitAlertAck == false || SS_outwitVoteAck == false) {
				//if (true) {
					var timer=doc.getElementById('liveObjectTimer');
					
					if (timer != null) {
						//alert('checking for contest');
						//smackPoll();
						setTimeout("smackPoll()",SS_alertTimeOut,);
					}
					if (_checkGuruGuess == true) {
					//	checkGuruGuess();
					  //checkGuruGuess();
						setTimeout("checkGuruGuess()",SS_alertTimeOut);
						
					}
			}
			*/
			}, true);
			
			
			chatDiv.addEventListener('click', function(event) {
				}, true);
	}
	
	
	var guru=doc.getElementById('guruContainer');
			if (guru != null){
				//alert('guru not null');
				guru.addEventListener('DOMAttrModified', function(event) {
					SS_AM.updateAlertState();
					/*
					var guruguessAlertPref = SS_getPreference(SMACK_GURUGUESSALERT);
					if (guruguessAlertPref == "alert" || guruguessAlertPref == "audio" || guruguessAlertPref == "both") {
						if (guru.style.display == "block") {
							_checkGuruGuess = true;
						} else if (guru.style.display == "none") {
							//alert('guruguess display is none');
							_checkGuruGuess = false;
						}
					}
					*/
				}, true);		
		} else {
			//alert('guru is null');
			//_checkGuruGuess = false;
		}

	var e1=doc.getElementsByName('user_guess');
	var guruinput;
	for (var i=0;i<e1.length;i++) {
	 	if (e1[i].name == 'user_guess') {
	 		guruinput = e1[i];
	 		//alert('AVL gg user guess found');
	 		break;
		}
	}
	if (guruinput != null) {
		if (SS_ggListenerAdded == false) {
			SS_ggListenerAdded = true;
		guruinput.addEventListener('dblclick', function(event) {
			launchCalcWindow();
			//	alert(document.defaultView.liveObject);
			//	alert(window["liveObject"].duration);
		}, true);
	}
	}
	else {
		SS_ggListenerAdded = false;
	}
	
}

function checkGuruGuess() {
	//if (doc == null) doc = content.document;
	///////////////////

	var e1=SS_doc.getElementsByName('user_guess');
	if (e1 != null) {
   		var guruinput;
   		for (var i=0;i<e1.length;i++) {
   		 	if (e1[i].name == 'user_guess') {
   		 		guruinput = e1[i];
   		 		//alert('AVL gg user guess found');
   		 		break;
   			}
   		}
   		if (guruinput != null) {
   			 if (SS_ggListenerAdded == false) {
		   		//	alert('GG add event list' + SS_ggListenerAdded);
		   			SS_ggListenerAdded = true;
		   			guruinput.addEventListener('dblclick', function(event) {
						//remove	openGGC(SS_doc);
						launchCalcWindow();
						//	alert(document.defaultView.liveObject);
						//	alert(window["liveObject"].duration);
							}, true);
				}
   		} else {
   			SS_ggListenerAdded = false;
   			//alert('guruinput NOT found, unable to perform calculations.SS_ggListenerAdded = false; ' + );
    	}
    		 
   	} //end e1
   	else {
   		//alert('SS_ggListenerAdded set to false');
   		SS_ggListenerAdded = false;
   	}
					
	////////////////////
		
			
	if (SS_guruguessAlertAck == false && SS_doc.getElementById(SMACK_OUTWITGURUGUESSDIV) != null) {
	//	alert(SS_guruguessAlertAck + ' (SS_guruguessAlertAck) checkGuruGuess found GG (div) ' + SS_doc.getElementById(SMACK_OUTWITGURUGUESSDIV));
		var guruguessAlertPref = SS_getPreference(SMACK_GURUGUESSALERT);
		//alert('guruguessAlertPref ' + guruguessAlertPref);
		SS_guruguessAlertAck = true;

		if (guruguessAlertPref == "audio" || guruguessAlertPref == "both"){
			//alert('play audio');
			playAudioAlert(DEFAULT_SOUND);
		}
		if (guruguessAlertPref == "alert" || guruguessAlertPref == "both"){
			//alert('show GG alert entered');
			var jellyfishstrings = document.getElementById("swaksmack-strings");
			var alert3 = jellyfishstrings.getString("guruguessWarn1");	
			//alert(alert3 +'\n'+Date());
			SS_AM.swakAlert(SMACK_ALERT_GURUGUESS, true, 60000, true);
		} else if (SS_doc.getElementById(SMACK_OUTWITGURUGUESSDIV) == null) {
			SS_guruguessAlertAck = false;
		}
	}
	else {
		//this constantly entered during a SD show after guess is in
		//alert(SS_guruguessAlertAck + ' (SS_guruguessAlertAck) checkGuruGuess failed to find GG (div) ' + SS_doc.getElementById(SMACK_OUTWITGURUGUESSDIV));
	}
}

var SS_oldState = null;
function smackPoll() {
	var cState = SS_AM.state;
	if (cState == SMACK_STATE_CONTEST_END || cState == SMACK_STATE_DEAL || cState == SMACK_STATE_GG_DEAL) {
		SS_outwitAlertAck = false;
		SS_outwitVoteAck = false;
		SS_guruguessAlertAck = false;
		return;
	}
	//another safety check since we don't have a real state machine to eval transistions
	if (SS_oldState == SMACK_STATE_DEAL && cState == SMACK_STATE_OW_OPTIN) {
		SS_outwitAlertAck = false;
		SS_outwitVoteAck = false;
		SS_guruguessAlertAck = false;
	}
	/*
	if (cState == SS_oldState) {
		return;
		
	}
	else {
		alert(SS_oldState + ' (old) diff state (new) ' + cState);
	}
	*/
	var outwitAlertPref = "none";
	var outwitVoteAlertPref = "none";
	var guruguessAlertPref = "none";
	try {
 		outwitAlertPref = SS_getPreference(SMACK_OUTWITALERT);
 		outwitVoteAlertPref = SS_getPreference(SMACK_OUTWITVOTEALERT);
 		guruguessAlertPref = SS_getPreference(SMACK_GURUGUESSALERT);
	}
	catch(Exception){}
	
	
	if (cState == SMACK_STATE_OW_OPTIN){
		if (outwitAlertPref == "both" || outwitAlertPref == "alert" || outwitAlertPref == "audio") {
			//alert('opt in state');
			if (SS_outwitAlertAck == false) {
				//alert('opt in state ack false--should get opt in alert');
				SS_outwitAlertAck = true;
				if (outwitAlertPref == "both" || outwitAlertPref == "audio"){
					playAudioAlert(DEFAULT_SOUND);
				}
				if (outwitAlertPref == "both" || outwitAlertPref == "alert"){
					//var jellyfishstrings = document.getElementById("swaksmack-strings");
					//var alert1 = jellyfishstrings.getString("outwitWarn1");
					//alert(alert1+'\n'+Date());
					SS_AM.swakAlert(SMACK_ALERT_OUTWITOPTIN, true, 60000, true);
				}
			}
		}
	}
	else if (cState == SMACK_STATE_OW_VOTE){
		if (outwitVoteAlertPref == "both" || outwitVoteAlertPref == "alert" || outwitVoteAlertPref == "audio") {
			if (SS_outwitVoteAck == false) {
				SS_outwitVoteAck = true;
				if (outwitVoteAlertPref == "both" || outwitVoteAlertPref == "audio") {
					playAudioAlert(DEFAULT_SOUND);
				}
				if (outwitVoteAlertPref == "both" || outwitVoteAlertPref == "alert") {
					SS_AM.swakAlert(SMACK_ALERT_OUTWITVOTE, true, 60000, true);
				}
			}
		}
	}
	else if (cState == SMACK_STATE_GG){
		//alert('smack poll state ' + cState);
		checkGuruGuess();
	}
	/*
	else {
		SS_outwitAlertAck = false;
		SS_outwitVoteAck = false;
		SS_guruguessAlertAck = false;
	}
	*/
}

function smackPoll_ORG() {
	var outwitAlertPref = "none";
	var outwitVoteAlertPref = "none";
	var guruguessAlertPref = "none";

  var owcapdiv = SS_doc.getElementById(SMACK_OUTWITCAPDIV);
  var owansdiv = SS_doc.getElementById(SMACK_OUTWITANSWERDIV);
  if (owcapdiv == null && owansdiv == null) {
  	SS_outwitAlertAck = false;
  	SS_outwitAlertAck = true;
  }

	
	try {
 		outwitAlertPref = SS_getPreference(SMACK_OUTWITALERT);
 		outwitVoteAlertPref = SS_getPreference(SMACK_OUTWITVOTEALERT);
 		guruguessAlertPref = SS_getPreference(SMACK_GURUGUESSALERT);
	}
	catch(Exception){}
	
	
	if (outwitAlertPref == "both" || outwitAlertPref == "alert" || outwitAlertPref == "audio") {
		if(SS_outwitAlertAck == false && owcapdiv != null){
			SS_outwitAlertAck = true;
			SS_outwitVoteAck = false;

			if (outwitAlertPref == "both" || outwitAlertPref == "audio"){
				playAudioAlert(DEFAULT_SOUND);
			}

			if (outwitAlertPref == "both" || outwitAlertPref == "alert"){
				var jellyfishstrings = document.getElementById("swaksmack-strings");
				var alert1 = jellyfishstrings.getString("outwitWarn1");
				//alert(alert1+'\n'+Date());
				SS_AM.swakAlert(SMACK_ALERT_OUTWITOPTIN, true, 60000, true);
			} 
		}		

		if (SS_outwitVoteAck == false && owansdiv != null) {
			SS_outwitAlertAck = false;
			SS_outwitVoteAck = true;
			if (outwitVoteAlertPref == "both" || outwitVoteAlertPref == "alert" || outwitVoteAlertPref == "audio") {
				if (outwitVoteAlertPref == "both" || outwitVoteAlertPref == "audio") {
					playAudioAlert(DEFAULT_SOUND);
				}

				if (outwitVoteAlertPref == "both" || outwitVoteAlertPref == "alert") {
					var randomGuess = Math.ceil(Math.random()*6);				
					var jellyfishstrings = document.getElementById("swaksmack-strings");
				 	var alert2 = jellyfishstrings.getString("outwitVoteWarn1");
				 	var outwitRandomPref = true;
				 	try {
				 		outwitRandomPref = SS_getPreference(SMACK_OUTWITRANDOM);	
					} catch(Exception){}
					if (outwitRandomPref){
						alert2 += "\n" + jellyfishstrings.getString("outwitRandom1") + randomGuess;
					}
					//alert(alert2);
					SS_AM.swakAlert(SMACK_ALERT_OUTWITVOTE, true, 60000, true);
				}
			}
		} 
	}


	if (guruguessAlertPref == "both" || guruguessAlertPref == "audio" || guruguessAlertPref == "alert"){
		//check here really still needed? 080107 --no harm I guess
		checkGuruGuess();
	}
}

// swaksmack context menu stuff

function swakContextVisibilityOn() {
var menuitem = document.getElementById("swaksmack-context-menu");
menuitem.setAttribute("hidden","false");
menuitem = document.getElementById("contextmenu-addkeywords");
menuitem.setAttribute("hidden","false");
menuitem = document.getElementById("contextmenu-listkeywords");
menuitem.setAttribute("hidden","false");
menuitem = document.getElementById("contextmenu-clearkeywords");
menuitem.setAttribute("hidden","false");
}

function swakContextShowing() {
	//alert('contextShowing');
  var menuitem = document.getElementById("contextmenu-addkeywords");
  if (gContextMenu.isTextSelected) {
      var keyword;
	  if (gContextMenu.searchSelected)
			keyword = gContextMenu.searchSelected();
		else
			keyword = getBrowserSelection();
      if (keyword.length > SS_keywordDisplayLength) 
		keyword = keyword.substr(0,SS_keywordDisplayLength-1) + "...";
      var displaytext = "Add \"" + keyword + "\" to SwakSmack highlights.";
      menuitem.setAttribute("label", displaytext);
      menuitem.setAttribute("hidden","false");
  }
  else {
  	menuitem.setAttribute("hidden","true");
  }
}

function chatAddKeywords() {
	//alert('Do keyword stuff');
		var keyword = "";
	if (gContextMenu.onTextInput) 
	{
		alert('Do keyword stuff on textinput');
		keyword = document.popupNode;
		keyword = keyword.value.substring(keyword.selectionStart, keyword.selectionEnd);
		if (keyword.length>SS_keywordDisplayLength) 
			keyword = keyword.substr(0,SS_keywordDisplayLength-1);
	}
		else 
	{
		if (gContextMenu.searchSelected)
			keyword = gContextMenu.searchSelected();
		else
			keyword = getBrowserSelection();
		if (keyword.length == 0)
		{
			//do nothing? /?an alert?
			return;
		}
	}
	if (keyword.length>0)
	{
		//keyword = keyword.replace(' ,',',').replace(', ',',').replace(' ','\s').split(','); // Allow for spaces in usernames
		//alert(keyword);
		SS_dynamicKeywords.push(keyword);
	}

	}
	
	function chatClearKeywords(){
		//clear the dynamic keywords
		//keywords specified in options are kept
		SS_dynamicKeywords = [];
	}

	function chatListKeywords(){
		//list keywords
		var words = SS_getPreference(SMACK_KEYWORDHL1);
		var usernames = SS_getPreference(SMACK_USERNAMEHL1);
		var list = 'SwakSmack Keywords\n';
		if (words != null && usernames != null) {
			list = list + '\nMain Keywords: \n';
			if (usernames != null) list = list + 'Usernames: ' + usernames +'\n';
			if (words != null) list = list + 'Keywords: ' + words +'\n';		
		}
		if (SS_dynamicKeywords !=null && SS_dynamicKeywords.length>0) {
			list = list + '\nDynamic Keywords: \n' +  SS_dynamicKeywords.toString();
		}
		
		alert(list);
}


//guru guess calc
function launchCalcWindow() {
    		 if (SS_GGCalcWindow == null || SS_GGCalcWindow.closed == true) {
    		
    		//showing the window assigns the popup ref to _SSGGCalcWindow
    		
    		
    		 //SS_GGCalcWindow=window.open('chrome://swaksmack/content/ggcalc.html','SwakSmack Guru Calculator','height=400,width=500');
    		 SS_GGCalcWindow=window.open('chrome://swaksmack/content/ggcalc.xul','SwakSmack Guru Calculator','height=400,width=500');

     		}
     		else {
     			//we close and then create a new window because some of the elements 
     			//the popup depends on are replaced whem the liveconatinerobject has
     			//its innherhtml updated
     			SS_GGCalcWindow.close();
     			// SS_GGCalcWindow=window.open('chrome://swaksmack/content/ggcalc.html','SwakSmack Guru Calculator','height=400,width=500');
     			 SS_GGCalcWindow=window.open('chrome://swaksmack/content/ggcalc.xul','SwakSmack Guru Calculator','height=400,width=500');

     		}

					
				//create popup object--revisit
     		 if ( SS_ggcalc == null) {
						SS_ggcalc = new GGCalc();
          }
          
          SS_ggcalc.popup=SS_GGCalcWindow;
          
          //check to see if the popup is fully loaded
       //   setTimeout('popupcheck()',100);
}

//is there a better way to tall when the child popup has loaded???
function popupcheck() {
	var gurucalcans = SS_GGCalcWindow.document.getElementById('gganswer');
   if (gurucalcans != null){
   	openGuruGuessCalc(content.document);
  	return;
  }
  //keep checking
  setTimeout('popupcheck()',100);
}

function openGuruGuessCalc(doc)
{ 
	alert('openGuruGuessCalc entry');
  if ( SS_ggcalc == null) {
		SS_ggcalc = new GGCalc();
  }
         
		                    
 
    	var retaildiv=doc.getElementById('retailPrice');
    	alert('retaildiv ' + retaildiv.textContent);
    	if (retaildiv != null){
    		var gurudiv = doc.getElementById('guruHasNick');
    		var e1=doc.getElementsByName('user_guess');
    		var guruinput;
    		for (var i=0;i<e1.length;i++) {
    		 	if (e1[i].name == 'user_guess') {
    		 		guruinput = e1[i];

    		 		break;
    			}
    		}
    		SS_ggcalc.showcalc(retaildiv.textContent, doc, guruinput);
 

     		  
     		                  
    	}
    	else {
    		var ggerror1 = SS_getStringTableText('ggcalc_error1');
    		alert(ggerror1);
    	}

    

       
}

var swaksmack = {
  onLoad: function() {
    // initialization code
    this.initialized = true;
    this.strings = document.getElementById("swaksmack-strings");
    document.getElementById("contentAreaContextMenu")
            .addEventListener("popupshowing", function(e) { this.showContextMenu(e); }, false);
    //add onload listener for web pages        
    var appcontent = document.getElementById("appcontent");   // browser
    if(appcontent) {
      appcontent.addEventListener("load", this.onPageLoad, true);  
      appcontent.addEventListener("load", this.showContextMenu, true);        
    }

          
  },
  onPageLoad: function(aEvent) {
     var doc = aEvent.originalTarget; // doc is document that triggered "onload" event
    // do something with the loaded page.
    // doc.location is a Location object (see below for a link).
    // You can use it to make your code executed on certain pages only.
   
    	/*
    if (window.title == window.opener.content.document.SS_GGCalcWindow.title) {
    	alert('GGCalc loaded');
    }
    */
  
    if (checkHost(doc) == true) {
    	//alert('onpageload');
    	//create a UID for this session
    		var d = new Date();
				SS_UID = d.getTime();
    	
    	//store doc ref for smack shopping document
    	if (isSmackShopArea(doc)) {
    		//alert('smack area found');
    	SS_doc = doc;
    	window.SS_doc = doc;
    	SS_window = window;
    }
    	//check to see if in the private message area
    	if (isPMArea(doc) == true) {
    		executePMLink(SMACK_PMDIV, doc);
    		return;
    	}
    //	alert('onpageload');
    	commentSpellCheck(doc);
    	chatLinkColor(doc);
    	
    	//REMOVE outwitAlertPref = SS_getPreference(SMACK_OUTWITALERT);
    	//REMOVE outwitVoteAlertPref = SS_getPreference(SMACK_OUTWITVOTEALERT);
    	//REMOVE guruguessAlertPref = SS_getPreference(SMACK_GURUGUESSALERT);

    	registerChatListeners(doc);
    	registerChatPostListener(doc);
    	SS_AM = new SSAlertManager();
    	
    	//menu stuff
    	  
    	  var menu = document.getElementById("contentAreaContextMenu");
    	  //alert(menu);
  			menu.addEventListener("popupshowing", swakContextShowing, false);
  			swakContextVisibilityOn();
			
    }
  },

  showContextMenu: function(event) {
    // show or hide the menuitem based on what the context menu is on
    // see http://kb.mozillazine.org/Adding_items_to_menus
    //document.getElementById("context-jellyfish").hidden = gContextMenu.onImage;  //org
    document.getElementById("context-swaksmack").hidden = !checkHost();
  },
  onMenuItemCommand: function(e) {
  	
  	//no longer needed for chat/url processing --remove menu item???
  	//execute(SMACK_OUTWITCHATDIV);
  	//externalLinks();

                                
  },

};
window.addEventListener("load", function(e) { swaksmack.onLoad(e); }, false);

